<template>
<section>
  <div>
    <input type="text" placeholder="输入城市名或拼音" v-model="keyword">
  </div>
  <div ref="search" v-show="keyword">
    <ul>
      <li
      v-for="item of list"
      :key="item.id"
      @click="handleCityClick(item.name)"
      >{{item.name}}</li>
      <li v-show="hasNoData">没有找到匹配数据</li>
    </ul>
  </div>
</section>
</template>
<script>
import Bscroll from 'better-scroll'
import {mapMutations} from 'vuex'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      timer: null,
      list: []
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  methods: {
    handleCityClick (city) {
      // this.$store.dispatch('changeCity', city)
      // this.$store.commit('changeCity', city)
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  }
}
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl'
section
  position: relative
div:first-child
  height: 2.8rem
  background: $bgColor
  padding-left: 1.0rem
  padding-right: 1.0rem
  padding-top: .6rem
input
  width: 100%
  height: 1.8rem
  line-height: 1.8rem
  text-align: center
  border-radius: .6rem
  color: #666
ul
  position: absolute
  top: 2.8rem
  left: 0
  right: 0
  background: #eee
  z-index: 1
li
  line-height: 1.6rem
  color: #666
  font-size: 1.4rem
  border-bottom-style: solid
  border-bottom-color: #ccc
  border-bottom-width: .1rem
</style>
